package com.wh.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wh.basic.vo.AjaxResult;
import com.wh.org.exception.BusinessException;
import com.wh.org.pojo.Department;
import com.wh.user.dao.IUserDao;
import com.wh.user.dao.LoginInfoDao;
import com.wh.user.dto.UserDto;
import com.wh.user.pojo.LoginInfo;
import com.wh.user.pojo.User;
import com.wh.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceimpl implements IUserService {
    @Autowired
    private IUserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginInfoDao loginInfoDao;

    @Override
    @Transactional
    public void add(User user){
        //处理颜值和密码
        String uuid = RandomUtil.randomString(32);
        String password = user.getPassword();
        password = SecureUtil.md5(password + uuid);
        user.setSalt(uuid);
        user.setPassword(password);

        //先添加logininfo
        LoginInfo loginInfo = new LoginInfo();
        BeanUtil.copyProperties(user,loginInfo);
        loginInfo.setDisable(true);  //启动
        loginInfo.setType(1);          //员工

        //添加user的数据
        user.setLogininfoId(loginInfo.getId());
        userDao.insert(user);

    }

    @Transactional
    @Override
    public void delById(Long id) {
        User user = userDao.selectById(id);
        //关联数据，先删除从表
        userDao.deleteById(id);
        loginInfoDao.deleteById(user.getLogininfoId());
    }
    @Override
    @Transactional
    public void upd(User user){
        //修改 --先处理密码
        if (user.getPassword()!=null){
            String password = user.getPassword();
            String randomString = RandomUtil.randomString(32);
            String md5 = SecureUtil.md5(password + randomString);
            user.setPassword(md5);
            user.setSalt(randomString);
        }
        //修改登录信息
        LoginInfo loginInfo = loginInfoDao.selectById(user.getLogininfoId());
        if (user.getLogininfoId()==null || loginInfo.getId()==null ){
             loginInfo = new LoginInfo();
        }

        //同步数据
        BeanUtil.copyProperties(user,loginInfo,"id");
        //设置状态
        loginInfo.setDisable(true);
        //判断有没有id 有的话就是修改，没有就是添加
        if (loginInfo.getId()==null){
            loginInfoDao.insert(loginInfo);
        }else {
            loginInfoDao.updateById(loginInfo);
            user.setLogininfoId(loginInfo.getId());
        }

        //更新员工信息
        userDao.updateById(user);

    }


    @Override
    public List<User> findAll() {
        return userDao.selectList(null);

    }

    @Override
    public User findById(Long id) {
        return userDao.selectById(id);

    }

    @Override
    public IPage<User> findByPage(User user) {
        return null;
    }

    @Transactional
    @Override
    public void patchDel(List<Long> ids) {
        List<User> userList = userDao.selectBatchIds(ids);
        List<Long> logininfoIds = userList.stream().map(emp -> emp.getLogininfoId()).collect(Collectors.toList());
        userDao.deleteBatchIds(ids);
        loginInfoDao.deleteBatchIds(logininfoIds);

    }

    /**
     * 手机号验证码注册，注册信息传到后台，进行注册保存信息
     *
     * @param userDto
     */
    @Override
    public void regisPhone(UserDto userDto) {
        String phone = userDto.getPhone();
        System.err.println(phone);
        String password = userDto.getPwd();
        String phoneCode = userDto.getPhoneCode();
        String passwordRepeat = userDto.getRePwd();
        System.err.println(password);
        System.err.println(phoneCode);
        System.err.println(passwordRepeat);

        //     1、   判空
        if (StrUtil.isEmpty(phone) || StrUtil.isEmpty(password) ||
                StrUtil.isEmpty(phoneCode) || StrUtil.isEmpty(passwordRepeat)) {
            throw new BusinessException("信息不能有空");
        }
        //     2、   手机号是否重复- 查询t_user表
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", phone);
        User user = userDao.selectOne(qw);
        if (user != null) {
            throw new BusinessException("手机号已经被注册，请登录");
        }
        //     3、   密码是否一致
        if (!password.equalsIgnoreCase(passwordRepeat)) {
            throw new BusinessException("两次密码不一致，重新输入");
        }

        //     4、   检验手机验证码是否正确，是否过期

        //4：校验手机验证码是否过期，是否正确
        Object redisPhoneCode = redisTemplate.opsForValue().get("register:" + phone);
        System.err.println(redisPhoneCode);
        if(redisPhoneCode == null){
            throw new BusinessException("手机验证码过期或不存在，请重新获取!!!");
        }
        if(!phoneCode.equals(redisPhoneCode.toString().split(":")[0])){  // code:时间戳
            throw new BusinessException("手机验证码错误!!!");
        }


        //     5、   保存
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(phone);
        loginInfo.setPhone(phone);
        String uuid = IdUtil.fastSimpleUUID();
        loginInfo.setSalt(uuid);

        String psw = SecureUtil.md5(password + uuid);
        loginInfo.setPassword(psw);
        loginInfo.setType(1);
        loginInfo.setDisable(true);
        loginInfoDao.insert(loginInfo);

        User user1 = BeanUtil.copyProperties(loginInfo, User.class, "id");
        user1.setState(1);
        user1.setCreatetime(LocalDateTime.now());
        user1.setLogininfoId(loginInfo.getId());

        userDao.insert(user1);

    }
}
